#include "uart.h"


/* uart start and set baudrate */
void uart_init(unsigned long baudrate)
{
    uint value;
    T2MOD = 0x00; // T2 output disable and set count up mode
    T2CON = 0x30; // set baudrate generator mode
    SCON = 0x40; // set uart at mode 1
    PCON = 0x00; // SMOD = 0 (not meaning)

    value = 65536 - fosc / 32 / baudrate;
    TH2 = value/ 256; // 
    TL2 = value % 256; //
    RCAP2H = TH2; // 
    RCAP2L = TL2; //
    TR2 = 1; // start T2 timer
}

void uart_enable_recv(void)
{
    REN = 1;
}

void uart_enable_it(void)
{
    EA = 1;
    ES = 1;
}

/* send msg througth uart */
void uart_send(uchar *c)
{
    while(*c != '\0')
    {
        SBUF= *c;
        while(!TI);
        TI = 0;
        c++;
    }
}

/* recv msg through uart */
void uart_recv(uchar * str, uchar num)
{
    while(num)
    {
        while(!RI);
        *str = SBUF;
        str ++;
        RI = 0;
        num --;
    }
    *str = '\0';
}

// void uart_rx_it(void) interrupt 4
// {
//     uchar s[2];
//     if(RI)
//     {
//         s[0] = SBUF;
//         s[1]='\0';
//         uart_send(s);
//         RI = 0;
//     }
// }